package testing;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Level;
import org.junit.Test;

import app_kvEcs.ECS;
import client.KVStore;
import junit.framework.TestCase;
import logger.LogSetup;
import common.messages.KVAdminMessage;
import common.messages.KVMessage;
import common.messages.MD5Hash;
import common.messages.MetaData;
import common.messages.KVMessage.StatusType;

public class PerformanceTest extends TestCase {
    static {
        try {
            new LogSetup("logs/testing/test.log", Level.ERROR);
            //new KVServer(50000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ECS ecs = new ECS("ECS.config");
    KVAdminMessage kvadmin = null;
    String ip = "";
    int port = 0;

    private KVStore kvClient;

    public void setUp() {
        ecs.initService(1);
        ecs.start();

        kvadmin = new KVAdminMessage();
        kvadmin.setMetaList(KVAdminMessage.sortMetaData(ecs.activeMap));

        List<MetaData> metaDatas = KVAdminMessage.sortMetaData(ecs.activeMap);
        for (MetaData m : metaDatas) {
            ip = m.getIp();
            port = Integer.parseInt(m.getPort());
        }
        kvClient = new KVStore(ip, port);
        try {
            kvClient.connect();
        } catch (Exception e) {
        }
    }

    public void tearDown() {
        kvClient.disconnect();
        ecs.stop();
        ecs.shutDown();

    }

    @Test
    public void testPut() {
        
        String key = "";
        String value = "";
        try {
            FileReader reader = new FileReader("./DataSet/inbox/1");
            BufferedReader br = new BufferedReader(reader);
            String string = null;
            String s1 = null;
            while ((s1 = br.readLine()) != null) {
                string += s1;
            }
            key = "1";
            value=string;
            System.out.println(value);


            br.close();
            reader.close();
        } catch (IOException e) {
            System.out.println("Please check your ecs.conf");
        }
        
        

        KVMessage response = null;
        Exception ex = null;

        try {
            response = kvClient.put(key, value);
        } catch (Exception e) {
            ex = e;
        }

        assertTrue(ex == null && response.getStatus() == StatusType.PUT_SUCCESS);

    }
    
    @Test
    public void testGet() {
        String key = "1";
        String value = "";
        KVMessage response = null;
        Exception ex = null;

        try {
            kvClient.put(key, value);
            response = kvClient.get(key);
        } catch (Exception e) {
            ex = e;
        }
        value = response.getValue();
        System.out.println(value);
        assertTrue(ex == null);
    }

}
